package com.njtoyo.taxi.admin.service.business.operation_rule.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverMarketing;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverRegionServiceArrangement;
import com.njtoyo.taxi.admin.mapper.master.entity.GeoDriverRegion;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverMarketingSituation;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverMarketingMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.GeoDriverRegionMapper;
import com.njtoyo.taxi.admin.rest.presenter.business.operation_rule.DriverMarketingPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.operation_rule.driver_marketing.DriverMarketingInfoServicePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.driver_marketing.DriverMarketingAddOrUpdateWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.driver_marketing.DriverMarketingQueryWrapper;
import com.njtoyo.taxi.admin.service.business.operation_rule.DriverMarketingService;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DriverMarketingServiceImpl implements DriverMarketingService {

    @Autowired
    private DriverMarketingMapper driverMarketingMapper;
    @Autowired
    private GeoDriverRegionMapper driverRegionMapper;

    @Override
    public RestResult list(DriverMarketingQueryWrapper wrapper) {

        if (ObjectUtil.isNotNull(wrapper.getCantonId())) {
            List<GeoDriverRegion> listByCantonIds = driverRegionMapper.getListByCantonId(wrapper.getCantonId());
            if (CollUtil.isNotEmpty(listByCantonIds)) {
                Long driverRegionId = listByCantonIds.get(0).getId();
                wrapper.setDriverRegionId(driverRegionId);
            }
        }
        Page<DriverMarketingPresenter> pages = driverMarketingMapper.getPage(new Page<>(wrapper.getCurrent(), wrapper.getSize()), wrapper);
        return RestResult.success(pages);
    }

    @Override
    public RestResult add(DriverMarketingAddOrUpdateWrapper wrapper) {
        DriverMarketing selectMarkting = driverMarketingMapper.selectOne(Wrappers.<DriverMarketing>lambdaQuery().eq(DriverMarketing::getDriverRegionId, wrapper.getDriverRegionId()));
        if (ObjectUtil.isNotNull(selectMarkting)) {
            return RestResult.failed("该运营区已配置规则");
        }

        DriverMarketing driverMarketing = new DriverMarketing();
        driverMarketing.setDriverRegionId(wrapper.getDriverRegionId());
        driverMarketing.setStartedAt(DateUtil.parseDateTime(wrapper.getStartDate()));
        driverMarketing.setEndedAt(DateUtil.parseDateTime(wrapper.getEndDate()));
        driverMarketing.setTitle(wrapper.getTitle());
        driverMarketing.setSituation(DriverMarketingSituation.online_ride_fixed);
        if ("fixed".equals(wrapper.getMode())) {
            driverMarketing.setSpecifics(JSON.toJSONString(Dict.create().set("fixed", wrapper.getFixed())));
        } else {
            driverMarketing.setSpecifics(JSON.toJSONString(Dict.create().set("ratio", wrapper.getRatio())));
        }
        List<Dict> timeQuantums = new ArrayList<>();
        for (int i = 0; i < wrapper.getTimeQuantum().length; i++) {
            if (StrUtil.isBlank(wrapper.getTimeQuantum()[i].getStartTime()) || StrUtil.isBlank(wrapper.getTimeQuantum()[i].getEndTime())) {
                continue;
            }

            Date startDate = DateUtil.parseDateTime(wrapper.getTimeQuantum()[i].getStartTime());
            Date endDate = DateUtil.parseDateTime(wrapper.getTimeQuantum()[i].getEndTime());

            startDate.setSeconds(0);
            endDate.setSeconds(0);
            Dict dict = Dict.create()
                    .set("s", DateUtil.format(startDate, DatePattern.NORM_TIME_PATTERN))
                    .set("e", DateUtil.format(endDate, DatePattern.NORM_TIME_PATTERN));
            timeQuantums.add(dict);
        }
        driverMarketing.setValidTime(JSON.toJSONString(timeQuantums));
        driverMarketingMapper.insert(driverMarketing);
        return RestResult.success();
    }

    @Override
    public RestResult deleteById(Long id) {
        driverMarketingMapper.deleteById(id);
        return RestResult.success();
    }

    @Override
    public RestResult getInfoById(Long id) {
        DriverMarketing driverMarketing = driverMarketingMapper.selectById(id);

        DriverMarketingInfoServicePresenter driverMarketingInfoServicePresenter = new DriverMarketingInfoServicePresenter()
                .setId(driverMarketing.getId())
                .setTitle(driverMarketing.getTitle())
                .setDriverRegionId(driverMarketing.getDriverRegionId())
                .setStartDate(DateUtil.formatDateTime(driverMarketing.getStartedAt()))
                .setEndDate(DateUtil.formatDateTime(driverMarketing.getEndedAt()));
        if (driverMarketing.getSpecifics().contains("ratio")) {
            driverMarketingInfoServicePresenter.setMode("ratio");
            BigDecimal ratio = JSON.parseObject(driverMarketing.getSpecifics()).getBigDecimal("ratio");
            driverMarketingInfoServicePresenter.setRatio(NumberUtil.mul(ratio, Convert.toBigDecimal(100)).toString());
        } else {
            driverMarketingInfoServicePresenter.setMode("fixed");
            driverMarketingInfoServicePresenter.setFixed(JSON.parseObject(driverMarketing.getSpecifics()).getString("fixed"));
        }
        JSONArray jsonArray = JSON.parseArray(driverMarketing.getValidTime());
        List<DriverMarketingInfoServicePresenter.TimeQuantum> list = new ArrayList<>();
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            DriverMarketingInfoServicePresenter.TimeQuantum timeQuantum = new DriverMarketingInfoServicePresenter.TimeQuantum();
            String strDate = DateUtil.formatDate(DateUtil.date());
            timeQuantum.setStartTime(strDate + " " + jsonObject.getString("s"));
            timeQuantum.setEndTime(strDate + " " + jsonObject.getString("e"));
            list.add(timeQuantum);
        }
        driverMarketingInfoServicePresenter.setTimeQuantum(list.stream().toArray(DriverMarketingInfoServicePresenter.TimeQuantum[]::new));
        return RestResult.success(driverMarketingInfoServicePresenter);
    }

    @Override
    public RestResult update(DriverMarketingAddOrUpdateWrapper wrapper) {
        DriverMarketing selectMarkting = driverMarketingMapper.selectOne(Wrappers.<DriverMarketing>lambdaQuery()
                .eq(DriverMarketing::getDriverRegionId, wrapper.getDriverRegionId())
                .not(i -> i.eq(DriverMarketing::getId, wrapper.getId())));
        if (ObjectUtil.isNotNull(selectMarkting)) {
            return RestResult.failed("该运营区已配置规则");
        }


        DriverMarketing driverMarketing = new DriverMarketing();
        driverMarketing.setId(wrapper.getId());
        driverMarketing.setDriverRegionId(wrapper.getDriverRegionId());
        driverMarketing.setStartedAt(DateUtil.parseDateTime(wrapper.getStartDate()));
        driverMarketing.setEndedAt(DateUtil.parseDateTime(wrapper.getEndDate()));
        driverMarketing.setTitle(wrapper.getTitle());
        driverMarketing.setSituation(DriverMarketingSituation.online_ride_fixed);
        if ("fixed".equals(wrapper.getMode())) {
            driverMarketing.setSpecifics(JSON.toJSONString(Dict.create().set("fixed", wrapper.getFixed())));
        } else {
            driverMarketing.setSpecifics(JSON.toJSONString(Dict.create().set("ratio", wrapper.getRatio())));
        }
        List<Dict> timeQuantums = new ArrayList<>();
        for (int i = 0; i < wrapper.getTimeQuantum().length; i++) {
            if (StrUtil.isBlank(wrapper.getTimeQuantum()[i].getStartTime()) || StrUtil.isBlank(wrapper.getTimeQuantum()[i].getEndTime())) {
                continue;
            }
            Date startDate = DateUtil.parseDateTime(wrapper.getTimeQuantum()[i].getStartTime());
            Date endDate = DateUtil.parseDateTime(wrapper.getTimeQuantum()[i].getEndTime());
            startDate.setSeconds(0);
            endDate.setSeconds(0);
            Dict dict = Dict.create()
                    .set("s", DateUtil.format(startDate, DatePattern.NORM_TIME_PATTERN))
                    .set("e", DateUtil.format(endDate, DatePattern.NORM_TIME_PATTERN));
            timeQuantums.add(dict);
        }
        driverMarketing.setValidTime(JSON.toJSONString(timeQuantums));
        driverMarketingMapper.updateById(driverMarketing);
        return RestResult.success();
    }

    @Override
    public RestResult updateActive(DriverMarketing driverMarketing) {
        driverMarketingMapper.updateById(driverMarketing);
        return RestResult.success();
    }
}
